﻿namespace PAR.Audio
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using NAudio.Dsp;

    public partial class SpectrumAnalyzer : UserControl
    {
        private const double yScale = 750;
        private const double xScale = 125;

        public SpectrumAnalyzer()
        {
            InitializeComponent();
        }

        public void Update(Complex[] fftResults)
        {
            for (int n = 0; n < fftResults.Length / 2; n++)
            {
                double intensity = Math.Sqrt(fftResults[n].X * fftResults[n].X + fftResults[n].Y * fftResults[n].Y);
                double yPos = intensity * yScale;

                AddResult(n, yPos);
            }
        }

        private void AddResult(int index, double power)
        {
            var p = new Point(CalculateXPos(index), power);
            if (index >= polyline1.Points.Count)
            {
                polyline1.Points.Add(p);
            }
            else
            {
                polyline1.Points[index] = p;
            }
        }

        private double CalculateXPos(int bin)
        {
            if (bin == 0) return 0;
            return Math.Log10(bin) * xScale;
        }
    }
}
